#pragma once

#include "comm.hpp"
using namespace std;

const int defaultid = -1; //默认shmid
const int gsize = 4096;   //shm大小

const string pathName = ".";
const int projId = 66;

const int gmod = 0666;

#define CREATER "creater"
#define USER "user"

class Shm
{
private:
    void CreateHelp(int flg)
    {
        printf("Key: 0x%x\n", _key);

        _shmid = shmget(_key, _size, flg);
        if(_shmid < 0)
        {
            ERR_EXIT("shmget");
        }
        printf("shmid: %d\n", _shmid);
    }

    //创建一个全新的共享内存
    void CreateShm()
    {
        CreateHelp(IPC_CREAT | IPC_EXCL | gmod);
    }

    void GetShm()
    {
        CreateHelp(IPC_CREAT);
    }

    // 挂接共享内存
    void Attach()
    {
        _startMem = shmat(_shmid, nullptr, 0);
        if((long long)_startMem < 0)
        {
            ERR_EXIT("shmat");
        }
        printf("attach success\n");
    }

    void Detach()
    {
        int n = shmdt(VirtualAddr());
        if(n == 0)
        {
            printf("detach success\n");
        }
    }

    //销毁共享内存
    void DestoryShm()
    {
        if(_shmid == defaultid) return;
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if(n >= 0)
        {
            printf("shmctl delete shm(%d): success! \n", _shmid);
        }
        else
        {
            ERR_EXIT("shmctl");
        }
    }

public:
    Shm(const string &pathname, int projid, const string &usertype)
        :_shmid(defaultid), 
        _size(gsize), 
        _startMem(nullptr),
        _usertype(usertype)
    {
        _key = ftok(pathname.c_str(), projid);
        if(_key < 0)
        {
            ERR_EXIT("ftok");
        }
        if(_usertype == CREATER)
            CreateShm();
        else if(_usertype == USER)
            GetShm();
        else
        {}
        Attach();
    }

    //获取起始地址
    void *VirtualAddr()
    {
        printf("virtualaddr: %p\n", _startMem);
        return _startMem;
    }

    int Size()
    {
        return _size;
    }

    void Attr()
    {
        struct shmid_ds ds;
        int n = shmctl(_shmid, IPC_STAT, &ds);
        printf("shm size: %ld\n", ds.shm_segsz);
    }

    ~Shm()
    {
        Detach();
        if(_usertype == CREATER)
            DestoryShm();
    }
private:
    int _shmid;
    key_t _key;
    int _size;
    void *_startMem;
    string _usertype;
};